package org.zhs.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.zhs.constants.SessionKeyConstants;
import org.zhs.util.MessageUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义一个拦截器,拦截所有不合法的请求,
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //选择请求前拦截,return true就是放行,return false就是拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        登陆成功之后,应该有用户的session
        Object loginUser = request.getSession().getAttribute("loginUser");
        String languageKey =
                (String) request.getSession()
                        .getAttribute(SessionKeyConstants.LANGUAGE_KEY);
//        如果有session,证明是合法用户,放行
        if (loginUser == null){
            //设置携带的参数,会在html中展示
            String tipMessage = MessageUtils.getTipMessage("login.fail.message",languageKey);
            request.setAttribute("msg",tipMessage);
            //没有访问权限,就携带本次请求参数,重定向到Index
            if(languageKey!=null && !"null".equals(languageKey)){
                request.setAttribute("l",languageKey);
            }
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else {
            return true;
        }
    }
}
